package app.controllers;

import app.Const;
import app.kit.SmsCodeKit;
import app.kit.SmsKit;
import app.models.member.Member;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import goja.mvc.Controller;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * <p>
 * The url forgetpwd Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class ForgetpwdController extends Controller {

    /**
     * The index route.
     * the url /forgetpwd
     * the view in index.ftl
     */
    public void index() {}


    public void sendsms() {
        String phone = getPara("phone");
        SmsKit.registered(phone);
        renderAjaxSuccess();
    }
    public void regphone() {
        String phone = getPara("phone");
        if (!Strings.isNullOrEmpty(phone)) {
            Member member = Member.dao.findbyPhone(phone);
            Map<String, String> result = Maps.newHashMap();
            if (member == null) {
                result.put("error", "该手机号码不存在,请更换!");
                renderJson(result);
            } else {
                result.put("ok", null);
                renderJson(result);
            }
        }
    }

    public void reset() {
        String phone = getPara("phone");
//        SmsKit.registered(phone);
        setAttr("phone", getPara("phone"));
    }

    //忘记密码操作
    public void change() {
        String code = getPara(Const.FIELD_CODE);
        String phone = getPara("phone");
        String password = getPara("password");
        String rpassword = getPara("rpassword");
        if (Strings.isNullOrEmpty(code)) {
            renderAjaxFailure("短信验证码不能为空");
            return;
        }
        if (Strings.isNullOrEmpty(password)) {
            renderAjaxFailure("新密码不能为空");
            return;
        } else if (password.length() < 6 || password.length() > 16) {
            renderAjaxFailure("新密码长度6~16位");
            return;
        }

        if (!SmsCodeKit.checkRegisted(phone, code)) {
            renderAjaxFailure("短信验证码不正确");
            return;
        }

        if (Strings.isNullOrEmpty(rpassword)) {
            renderAjaxFailure("确认密码不能为空");
        } else if (!StringUtils.equals(rpassword, password)) {
            renderAjaxFailure("确认密码和新密码不一致");
        }
        Member member = Member.dao.findbyPhone(phone);
        member.generatePassword(password);
        boolean isOk = member.update();
        if (isOk) {
            renderAjaxSuccess();
        } else {
            renderAjaxError("修改失败");
        }
    }

    //忘记密码操作完成
    public void ok() {

    }
}